<template>
  <div class="public_height100 p20 pub_bgColorFFF">
    <div class="table_content">
      <!-- ====== 表格上方的筛选条件 start ======-->
      <div class="table_filter flex_space_between">
        <div class="flr">
          <div class="table_filter_search w300 mr20">
            <el-input v-model="params.commonSearch" class="pub_input pub_input_search" placeholder="搜索账号/姓名" clearable @keydown.enter.native="handleSearch" @clear="handleSearch">
              <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
            </el-input>
          </div>
          <div class="table_filter_search w300">
            <el-button type="text" class="public_confirm_btn pub_button" @click="handleSearch"> 搜索 </el-button>
          </div>
        </div>
        <div class="flex_end">
          <div>
            <el-button type="text" class="w108 pub_button pub_buttonGreen" @click="showDilogBtn('addDialogVisible')">
              <img src="@/assets/img/orderManagement/add.png" alt="新增订单" />
              <span class="ml5">添加账户</span>
            </el-button>
          </div>
          <div class="ml12">
            <el-button type="text" class="w108 pub_button pub_buttonRed" @click="delteDataBtn">
              <img src="@/assets/img/orderManagement/delete.png" alt="批量删除" />
              <span class="ml5">批量删除</span>
            </el-button>
          </div>
        </div>
      </div>
      <!-- ====== 表格上方的筛选条件 end ======-->
      <el-table ref="multipleTable" border size="mini" :data="tableData" tooltip-effect="dark" :height="`${536 * $f}px`" class="wp100 mt12" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" :width="`${50 * $f}`" />
        <el-table-column label="账号" prop="username" align="center" :width="`${150 * $f}`" />
        <el-table-column label="所属公司" prop="companyName" align="center" />
        <el-table-column label="类型" align="center" :width="`${80 * $f}`">
          <template slot-scope="scope">
            <span>{{ scope.row.type === 'admin' ? '管理员' : '员工' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="realName" label="姓名" align="center" :width="`${120 * $f}`" />
        <el-table-column prop="phoneNumber" label="手机号" align="center" :width="`${120 * $f}`" />
        <el-table-column prop="createTime" label="创建时间" align="center" :width="`${160 * $f}`" />
        <el-table-column prop="expireTime" align="center" :width="`${160 * $f}`">
          <template slot="header">
            <span>到期时间</span>
            <el-tooltip placement="top">
              <div slot="content">整个账号到期时间，充值会员会同步更新</div>
              <i class="el-icon-question" style="color:#606266;cursor:help;" />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="共享数据" align="center" :width="`${100 * $f}`">
          <template slot="header">
            <span>共享数据</span>
            <el-tooltip placement="top">
              <div slot="content">共享组内成员可以查看组内所有成员创建的订单和客户信息</div>
              <i class="el-icon-question" style="color:#606266;cursor:help;" />
            </el-tooltip>
          </template>
          <template slot-scope="{ row }">
            <el-button type="text" class="pub_button public_1EB398_btn" size="mini" @click="distributeBtnClick(row)">共享账号</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" :width="`${250 * $f}`">
          <template slot-scope="{ row }">
            <el-button v-if="row.type !== 'admin' && row.status === '1'" type="text" class="pub_button public_1EB398_btn" size="mini" @click="enableBtnClick(row)">禁用</el-button>
            <el-button v-if="row.type !== 'admin' && row.status !== '1'" type="text" class="pub_button public_1EB398_btn" size="mini" @click="enableBtnClick(row)">启用</el-button>
            <el-button v-if="row.type !== 'admin'" type="text" class="pub_button public_1EB398_btn" size="mini" @click="resetBtnClick(row)">密码重置</el-button>
            <el-button v-if="row.type !== 'admin'" type="text" class="pub_button public_1EB398_btn" size="mini" @click="editBtnClick(row)">编辑</el-button>
            <el-button v-if="row.type !== 'admin'" type="text" class="pub_button public_F16363_btn" size="mini" @click="delBtnClick(row)">删除</el-button>
          </template>
        </el-table-column>
        <template slot="empty">
          <PageEmptyData />
        </template>
      </el-table>
    </div>
    <!-- 提示添加公司 -->
    <PageDialog :title="'提示'" :dialog-visible="tipDialogVisible" :width="`${$f * 400}px`" @close="closeDialog" @submit="confirmAddCompany">
      <div class="pub_tips">
        请先添加公司
      </div>
    </PageDialog>
    <!-- 删除提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deleteDialogVisible" @close="closeDialog" @submit="confirmDelete" />
    <!-- 重置密码 -->
    <PageDialog :title="'密码重置'" :dialog-visible="resetPasDialogVisible" :width="`${400 * $f}px`" @close="closeDialog" @submit="confirmResetPas">
      <el-form ref="resetForm" :model="resetParams" :rules="resetRules" label-width="5rem" class="pub_form_item">
        <el-form-item label="密码重置" prop="password">
          <el-input v-model="resetParams.password" placeholder="请输入密码" class="pub_input" :maxlength="15" show-password />
        </el-form-item>
      </el-form>
    </PageDialog>
    <!-- 共享 -->
    <PageDialog :title="'共享数据'" :dialog-visible="showdDistribute" :width="`${800 * $f}px`" :height="`${500 * $f}px`" :submit-text="'提交'" @close="closeDialog" @submit="debounceConfirmDistribute">
      <el-transfer v-model="transferValue" :data="transferData" :titles="['待共享用户', '本共享组用户']" :button-texts="['', '']" :render-content="renderTransferItem" />
    </PageDialog>
    <!-- 添加账户 -->
    <PageDialog title="账号信息" :dialog-visible="addDialogVisible" :width="`${600 * $f}px`" @close="closeDialog" @submit="confirmAccount">
      <el-form ref="ruleForm" :model="addParams" :rules="rules" label-width="5rem" class="pub_form_item">
        <el-form-item label="公司名称" prop="companyId">
          <el-select v-model="addParams.companyId" placeholder="请选择公司" class="pub_select">
            <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="addParams.username" placeholder="请输入账号" class="pub_input" :maxlength="15" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addParams.password" placeholder="请输入密码" class="pub_input" :maxlength="15" show-password />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="addParams.realName" placeholder="请输入姓名" class="pub_input" :maxlength="5" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="addParams.phoneNumber" placeholder="请输入手机号" class="pub_input" :maxlength="11"> </el-input>
        </el-form-item>
      </el-form>
    </PageDialog>
  </div>
</template>
<script>
import tableFun from '@/mixin/tableFun.js';
import { debounce } from '@/utils/debounce.js';
export default {
  mixins: [tableFun],
  data() {
    // 密码验证规则
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'));
      } else if (this.$rules.isValidPassword(value) == false) {
        callback(new Error('密码只能是字母数字特殊字符大小写四选三'));
      } else {
        callback();
      }
    };
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      let reg = /^1(3[0-9]|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8[0-9]|9[0-9])\d{8}$/;
      if (!value) {
        callback(new Error('请输入手机号'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确手机号'));
      } else {
        callback();
      }
    };
    return {
      resetPasDialogVisible: false, //重置密码弹窗
      tipDialogVisible: false, //添加公司弹窗提示
      showdDistribute: false,
      shareList: [],
      params: { commonSearch: '' },
      resetParams: { password: '', id: '' },
      addParams: { username: '', password: '', companyName: '', companyId: '', realName: '', phoneNumber: '' },
      checked: [],
      curItem: {},
      companyList: [], //公司列表
      transferValue: [], // transfer组件的值
      transferData: [], // transfer组件的数据
      // 账号表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 1, max: 15, message: '账号长度不超过15个字符', trigger: 'blur' }
        ],
        password: [{ required: true, validator: validatePassword, trigger: 'blur' }],
        companyId: [{ required: true, message: '请选择公司', trigger: 'change' }],
        realName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 5, message: '姓名长度不超过5个字符', trigger: 'blur' }
        ],
        phoneNumber: [{ validator: validatePhone, trigger: 'blur' }]
      },
      // 重置密码表单验证规则
      resetRules: {
        password: [{ required: true, validator: validatePassword, trigger: 'blur' }]
      }
    };
  },
  created() {
    this.getCompanyList();
  },
  mounted() {},
  methods: {
    //关闭弹窗
    closeDialog() {
      this.addDialogVisible = false;
      this.deleteDialogVisible = false;
      this.tipDialogVisible = false;
      this.resetPasDialogVisible = false;
      this.showdDistribute = false;
      this.addParams = Object.assign({}, this.$options.data());
    },
    //获取公司列表
    async getCompanyList() {
      let { data } = await this.$api.get(this.$url.companyAll);
      if (data.length === 0) {
        this.tipDialogVisible = true;
      } else {
        this.companyList = data;
        this.getDataList();
      }
    },
    //获取表格数据
    async getDataList() {
      // 获取员工数据
      let { data } = await this.$api.get(this.$url.queryAllStaff, this.params);
      let staffData = data || [];
      // 添加员工类型标识
      staffData.forEach(el => {
        this.$set(el, 'type', 'staff');
      });
      // 获取管理员数据并添加到列表中
      try {
        // 这里假设已经通过 this.$store 或者全局变量可以获取到当前登录的管理员信息
        const adminInfo = this.$store.state.userInfo;
        if (adminInfo && adminInfo.username) {
          // 确保管理员信息有必要的字段
          const adminData = {
            ...adminInfo,
            type: 'admin',
            companyId: adminInfo.companyId || '',
            companyName: '所有公司',
            createTime: '--',
            phoneNumber: adminInfo.phoneNumber,
            shareGroupId: adminInfo.shareGroupId || '',
            realName: adminInfo.realName || '',
            status: '1' // 管理员默认启用状态
          };
          // 将管理员添加到数据列表前面
          staffData.unshift(adminData);
        }
      } catch (error) {
        console.warn('获取管理员信息失败:', error);
      }
      this.tableData = staffData;
      this.tableData.forEach(el => {
        this.companyList.forEach(son => {
          if (son.id === el.companyId && !el.companyName) {
            this.$set(el, 'companyName', son.companyName);
          }
        });
      });
    },
    // 共享按钮点击事件
    async distributeBtnClick(item) {
      this.curItem = JSON.parse(JSON.stringify(item));
      // 设置transfer数据
      // transferValue已共享的账号在右侧（v-model中）
      let sharedIds = [];
      if (item.shareGroupId) {
        // 查找tableData中具有相同shareGroupId的账号
        const sharedUsers = this.tableData.filter(user => user.shareGroupId === item.shareGroupId);
        sharedIds = sharedUsers.map(user => user.id);
        // 确保当前账号在已共享列表中
        if (!sharedIds.includes(item.id)) {
          sharedIds.push(item.id);
        }
      } else {
        // 新建共享组时，当前账号需要在已共享列表中
        sharedIds = [item.id];
      }
      // 已共享的账号在右侧（v-model中）
      this.transferValue = JSON.parse(JSON.stringify(sharedIds));
      // transfer的data为tableData中未在已共享列表中的账号，这些用户将显示在数据共享组件的左侧，供选择加入当前共享组
      // 过滤条件：选取没有共享组的用户，或者与当前操作项(item)属于同一个共享组的用户
      let data1 = this.tableData.filter(user => !user.shareGroupId || user.shareGroupId === item.shareGroupId);
      this.transferData = data1.map(user => ({
        key: user.id,
        label: `${user.username}/${user.realName}`,
        username: user.username,
        realName: user.realName,
        disabled: item.id === user.id
      }));
      this.showdDistribute = true;
    },
    // render transfer item内容
    renderTransferItem(h, option) {
      return h('div', [h('span', option.username), h('span', { style: { marginLeft: '10px', color: '#999' } }, option.realName)]);
    },
    // 防抖处理的确认共享方法
    debounceConfirmDistribute: debounce(function() {
      // 去掉必须选择2个以上账号的全局条件检查，具体逻辑在confirmDistribute中处理
      this.confirmDistribute();
    }, 500),
    async confirmDistribute() {
      const params = [];
      // 新增共享组情况（curItem.shareGroupId为空）
      if (!this.curItem.shareGroupId) {
        if (this.transferValue.length < 2) {
          this.$message.warning('必须2个以上账号才能组成共享数据组');
          return;
        }
        params.push({ shareGroupId: undefined, userIds: this.transferValue });
      } else if (this.transferValue.length > 0) {
        params.push({
          shareGroupId: this.curItem.shareGroupId,
          userIds: this.transferValue.length >= 2 ? this.transferValue : [] // 低于2条则传空数组
        });
      }
      let res = await this.$api.post(this.$url.distribute, params);
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('所选用户已共享订单及客户信息');
        // 刷新当前用户信息
        let req = await this.$api.get(this.$url.queryUserInfo);
        this.$store.commit('setUserInfo', { ...req.data, roleType: this.$store.state?.userInfo?.roleType });
        this.getDataList(); // 刷新列表数据
      } else {
        this.$message.success('订单及客户信息共享失败');
      }
    },
    //禁用启用
    async enableBtnClick(item) {
      await this.$api.post(this.$url.modifyStaffStatus, { id: item.id, status: item.status === '1' ? '2' : '1' });
      //状态还没变
      this.$message.success(`${item.status === '1' ? '禁用' : '启用'}成功`);
      this.getDataList();
    },
    //删除员工
    delBtnClick(val) {
      this.selectedRow = JSON.parse(JSON.stringify(val));
      this.showDilogBtn('deleteDialogVisible');
    },
    //确认删除
    async confirmDelete() {
      let res = null;
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        let idArr = this.multipleSelection.map(val => val.id);
        res = await this.$api.post(this.$url.deleteStaffs, idArr);
      } else {
        res = await this.$api.post(this.$url.deleteStaff, { id: this.selectedRow.id });
      }
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('删除成功');
        this.getDataList();
      } else {
        this.$message.success('删除失败');
      }
    },
    //重置密码
    async resetBtnClick(val) {
      this.resetParams = { ...val };
      this.resetPasDialogVisible = true;
    },
    //确认重置密码
    async confirmResetPas() {
      this.$refs.resetForm.validate(async valid => {
        if (valid) {
          let res = await this.$api.post(this.$url.resetStaffPassword, { id: this.resetParams.id, password: this.resetParams.password });
          this.closeDialog();
          if (res.code === 200) {
            this.$message.success('密码已重置为');
          } else {
            this.$message.success('重置失败');
          }
        }
      });
    },
    //搜索
    handleSearch() {
      this.getDataList();
    },
    //添加账号
    async confirmAccount() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let { id } = this.addParams;
          let url = id ? this.$url.updateStaff : this.$url.createStaff;
          let res = await this.$api.post(url, { ...this.addParams, expireTime: new Date(this.addParams.expireTime).getTime() });
          if (res.code === 200) {
            this.closeDialog();
            this.getDataList();
            this.$message.success(id ? '更新成功' : '新增成功');
          }
        }
      });
    },
    confirmAddCompany() {
      this.$router.push({ path: '/layout/company' });
    }
  }
};
</script>
<style lang="less" scoped>
.table_content {
  height: calc(100% - 49px);
}
::v-deep {
  .el-checkbox {
    margin: 4px 0 !important;
  }
  .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #27c1a5;
  }
  .el-checkbox__inner:hover {
    border-color: #27c1a5;
  }
  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #27c1a5;
    border-color: #27c1a5;
  }
  /* Transfer组件绿色主题 - 完整 */
  /* 项目项样式 */
  .el-transfer-panel__item {
    &.is-checked {
      color: #27c1a5;
      background-color: rgba(39, 193, 165, 0.1);
    }
    &:hover {
      color: #27c1a5;
      background-color: rgba(39, 193, 165, 0.05);
    }
    /* 确保复选框在item中也是绿色 */
    .el-checkbox__input.is-checked + .el-checkbox__label {
      color: #27c1a5 !important;
    }
  }
  /* 面板样式 - 增加宽度 */
  .el-transfer-panel {
    width: 285px; /* 增加面板宽度 */
    border-color: #e4e7ed;
    &__header {
      color: #333;
    }
    &__footer {
      border-top-color: #e4e7ed;
    }
  }
  /* 确保Transfer组件整体宽度适配 */
  .el-transfer {
    width: 100%;
  }
  /* 按钮样式 */
  .el-button--primary {
    background-color: #27c1a5 !important;
    border-color: #27c1a5 !important;
    &:hover {
      background-color: #22a98e !important;
      border-color: #22a98e !important;
    }
    &:focus {
      background-color: #22a98e !important;
      border-color: #22a98e !important;
    }
    &.is-disabled {
      background-color: #b3f0e6 !important;
      border-color: #b3f0e6 !important;
    }
  }
  /* 穿梭按钮组样式 */
  .el-transfer__buttons {
    .el-button {
      &:hover {
        color: #27c1a5;
        border-color: #27c1a5;
        background-color: #f0f9f7;
      }
      /* 鼠标悬停时箭头图标显示为白色 */
      &:hover .el-icon-arrow-left {
        color: #fff;
      }
    }
  }
  /* 全选按钮样式 */
  .el-transfer-panel__checkbox {
    .el-checkbox__input {
      &:hover .el-checkbox__inner {
        border-color: #27c1a5;
      }
      &.is-checked .el-checkbox__inner {
        background-color: #27c1a5;
        border-color: #27c1a5;
      }
    }
  }
}
</style>
